#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:3年内企业涉金融信用类诉讼次数
code:EG_LawsuitCreditInThree
tableName:
columnName:
groups:准入>企业业务信息校验
dependencies:EG_CASE_DSJ
type:常用指标
dataSourceType:在线指标
description:
eof'''
import sys
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')

last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d') \
                  for i in [3, 0]]
null_type_list = ['', None, 'null', 'Null', 'NULL', '/']
fiance_list = [u'银行', u'分行', u'支行', u'小额贷款', u'信用卡', u'贷记卡', u'买卖', u'担保', u'付款', u'借款', u'利息', u'结算', u'债权', u'借贷']


def FormatData(tableName):
    try:
        eg = EG_CASE_DSJ.get("data").get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


def Ktgg_CpwsInThree():
    litigationList = FormatData("R227")
    if litigationList == [{}]:
        return u'缺失值'
    else:
        if len(litigationList) >= 1:
            duplicate_list = []
            resultList = []
            flag = False
            for i in litigationList:
                CASEDATE = i.get("CASEDATE")
                try:
                    CASEDATE = Formate(CASEDATE[:10])
                except:
                    CASEDATE = None
                CASENO = i.get("CASENO")
                PTYPE = i.get("PTYPE")
                TARGET = i.get("TARGET")
                PDESC = i.get("PDESC")
                if CASEDATE not in null_type_list and CASENO not in null_type_list and \
                        TARGET not in null_type_list and PDESC not in null_type_list and \
                        PTYPE not in null_type_list and CASENO not in duplicate_list:
                    duplicate_list.append(CASENO)
                    flag = True
                    if (PTYPE == "16" or PTYPE == "15") and last_year_list[0] < CASEDATE < last_year_list[1] and \
                            (len(filter(lambda x: x in TARGET, fiance_list)) != 0 or
                             (len(filter(lambda x: x in PDESC, fiance_list)) != 0)):
                        resultList.append(1)
            return len(resultList) if flag else u'缺失值'
        else:
            return 0


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


if __name__ == '__main__':
    import json

    file_obj = open(r'../../data/EG_LawsuitCreditInThree/EG_CASE_DSJ.json', 'r')
    content = file_obj.read()
    EG_CASE_DSJ = json.loads(content, strict=False)
    aa = Ktgg_CpwsInThree()
    print aa

result = Ktgg_CpwsInThree()
